package com.xc.stock.enhance.eventbus;

import java.util.concurrent.Executors;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.xc.stock.enhance.opentracing.concurrent.TracingExecutorService;
import com.xc.stock.utils.SpringUtils;


public class EventBusCenter implements BeanPostProcessor {
	// 管理同步事件
	private EventBus syncEventBus = new EventBus();

	// 管理异步事件
	private AsyncEventBus asyncEventBus = new AsyncEventBus(TracingExecutorService.get(Executors.newCachedThreadPool()));

	public void postSync(Object event) {
		syncEventBus.post(event);
	}

	public void postAsync(Object event) {
		asyncEventBus.post(event);
	}
	
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		EventBusListener annotation = AnnotationUtils.findAnnotation(bean.getClass(), EventBusListener.class);
		if(annotation != null) {
			asyncEventBus.register(bean);
			syncEventBus.register(bean);
		}
		return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
	}
	
	public static EventBusCenter of() {
		return SpringUtils.getBean(EventBusCenter.class);
	}

}
